<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-button @click="goBack" size="small">
              <el-icon><Back /></el-icon>
            </el-button>
            <span class="dict-title">
              {{ dictInfo.name }} ({{ dictInfo.type }})
            </span>
          </div>
          <div>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon> 新增
            </el-button>
            <el-button type="success" @click="refreshList">
              <el-icon><Refresh /></el-icon> 刷新
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="数据标签">
          <el-input v-model="queryParams.label" placeholder="请输入数据标签" clearable @keyup.enter="searchList" />
        </el-form-item>
        <el-form-item label="数据键值">
          <el-input v-model="queryParams.value" placeholder="请输入数据键值" clearable @keyup.enter="searchList" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchList">
            <el-icon><Search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 字典数据表格 -->
      <el-table v-loading="loading" :data="dataList" border>
        <el-table-column prop="id" label="数据编号" width="80" />
        <el-table-column prop="label" label="数据标签" width="150" />
        <el-table-column prop="value" label="数据键值" width="150" />
        <el-table-column prop="sort" label="排序" width="60" />
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="css_class" label="样式属性" width="120">
          <template #default="scope">
            <el-tag v-if="row.css_class" :type="row.css_class">{{ row.label }}</el-tag>
            <span v-else>{{ row.css_class }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="list_class" label="回显样式" width="120">
          <template #default="scope">
            <el-tag v-if="row.list_class" :type="row.list_class">{{ row.label }}</el-tag>
            <span v-else>{{ row.list_class }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="is_default" label="是否默认" width="80">
          <template #default="scope">
            <el-tag :type="row.is_default === 1 ? 'success' : 'info'">
              {{ row.is_default === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column prop="create_time" label="创建时间" width="180" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row.id)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        class="pagination"
        :current-page="queryParams.page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加/编辑字典数据对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      destroy-on-close
      @closed="resetForm"
    >
      <el-form
        ref="dictDataFormRef"
        :model="dictDataForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="字典类型" prop="dict_type">
          <el-input v-model="dictDataForm.dict_type" disabled />
        </el-form-item>
        <el-form-item label="数据标签" prop="label">
          <el-input v-model="dictDataForm.label" placeholder="请输入数据标签" />
        </el-form-item>
        <el-form-item label="数据键值" prop="value">
          <el-input v-model="dictDataForm.value" placeholder="请输入数据键值" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="dictDataForm.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="dictDataForm.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="样式属性" prop="css_class">
          <el-select v-model="dictDataForm.css_class" placeholder="请选择样式" clearable>
            <el-option label="默认" value="" />
            <el-option label="主要" value="primary">
              <el-tag type="primary">主要</el-tag>
            </el-option>
            <el-option label="成功" value="success">
              <el-tag type="success">成功</el-tag>
            </el-option>
            <el-option label="信息" value="info">
              <el-tag type="info">信息</el-tag>
            </el-option>
            <el-option label="警告" value="warning">
              <el-tag type="warning">警告</el-tag>
            </el-option>
            <el-option label="危险" value="danger">
              <el-tag type="danger">危险</el-tag>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="回显样式" prop="list_class">
          <el-select v-model="dictDataForm.list_class" placeholder="请选择样式" clearable>
            <el-option label="默认" value="" />
            <el-option label="主要" value="primary">
              <el-tag type="primary">主要</el-tag>
            </el-option>
            <el-option label="成功" value="success">
              <el-tag type="success">成功</el-tag>
            </el-option>
            <el-option label="信息" value="info">
              <el-tag type="info">信息</el-tag>
            </el-option>
            <el-option label="警告" value="warning">
              <el-tag type="warning">警告</el-tag>
            </el-option>
            <el-option label="危险" value="danger">
              <el-tag type="danger">危险</el-tag>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否默认" prop="is_default">
          <el-radio-group v-model="dictDataForm.is_default">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="dictDataForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getDictTypeDetail,
  getDictDataList,
  getDictDataDetail,
  addDictData,
  editDictData,
  deleteDictData
} from '@/api/system'
import {
  Plus, Refresh, Search, Edit, Delete, Back
} from '@element-plus/icons-vue'

// 获取路由实例
const route = useRoute()
const router = useRouter()

// 字典类型信息
const dictInfo = reactive({
  id: 0,
  name: '',
  type: ''
})

// 列表数据
const dataList = ref([])
const total = ref(0)
const loading = ref(false)

// 查询参数
const queryParams = reactive({
  dict_type_id: 0,
  label: '',
  value: '',
  status: '',
  page: 1,
  pageSize: 10
})

// 表单相关
const dictDataFormRef = ref(null)
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = computed(() => isEdit.value ? '编辑字典数据' : '新增字典数据')

// 表单数据
const dictDataForm = reactive({
  id: undefined,
  dict_type_id: 0,
  dict_type: '',
  label: '',
  value: '',
  sort: 0,
  status: 1,
  css_class: '',
  list_class: '',
  is_default: 0,
  remark: ''
})

// 表单验证规则
const rules = {
  label: [{ required: true, message: '数据标签不能为空', trigger: 'blur' }],
  value: [{ required: true, message: '数据键值不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
}

// 初始化
onMounted(() => {
  const dictTypeId = parseInt(route.params.id)
  const dictName = route.query.dictName
  const dictType = route.query.dictType
  
  if (dictTypeId && dictName && dictType) {
    dictInfo.id = dictTypeId
    dictInfo.name = dictName
    dictInfo.type = dictType
    queryParams.dict_type_id = dictTypeId
    
    getList()
  } else {
    // 如果缺少参数，先获取字典类型详情
    getDictTypeInfo(dictTypeId)
  }
})

// 获取字典类型详情
const getDictTypeInfo = async (id) => {
  try {
    const res = await getDictTypeDetail(id)
    dictInfo.id = res.data.id
    dictInfo.name = res.data.name
    dictInfo.type = res.data.type
    queryParams.dict_type_id = res.data.id
    
    getList()
  } catch (error) {
    console.error(error)
    ElMessage.error('获取字典类型详情失败')
  }
}

// 获取字典数据列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getDictDataList(queryParams)
    dataList.value = res.data.data
    total.value = res.data.total
  } catch (error) {
    console.error(error)
    ElMessage.error('获取字典数据列表失败')
  } finally {
    loading.value = false
  }
}

// 返回字典类型列表
const goBack = () => {
  router.push('/system/dict')
}

// 刷新列表
const refreshList = () => {
  getList()
}

// 搜索列表
const searchList = () => {
  queryParams.page = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.label = ''
  queryParams.value = ''
  queryParams.status = ''
  queryParams.page = 1
  getList()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  getList()
}

// 点击新增按钮
const handleAdd = () => {
  dictDataForm.dict_type_id = dictInfo.id
  dictDataForm.dict_type = dictInfo.type
  isEdit.value = false
  dialogVisible.value = true
}

// 点击编辑按钮
const handleEdit = async (row) => {
  try {
    const res = await getDictDataDetail(row.id)
    Object.assign(dictDataForm, res.data)
    isEdit.value = true
    dialogVisible.value = true
  } catch (error) {
    console.error(error)
    ElMessage.error('获取字典数据详情失败')
  }
}

// 点击删除按钮
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该字典数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteDictData(id)
      ElMessage.success(res.msg || '删除成功')
      getList()
    } catch (error) {
      console.error(error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 重置表单
const resetForm = () => {
  if (dictDataFormRef.value) {
    dictDataFormRef.value.resetFields()
  }
  
  Object.assign(dictDataForm, {
    id: undefined,
    dict_type_id: dictInfo.id,
    dict_type: dictInfo.type,
    label: '',
    value: '',
    sort: 0,
    status: 1,
    css_class: '',
    list_class: '',
    is_default: 0,
    remark: ''
  })
}

// 提交表单
const submitForm = () => {
  dictDataFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      if (isEdit.value) {
        const res = await editDictData(dictDataForm)
        ElMessage.success(res.msg || '修改成功')
      } else {
        const res = await addDictData(dictDataForm)
        ElMessage.success(res.msg || '添加成功')
      }
      
      dialogVisible.value = false
      getList()
    } catch (error) {
      console.error(error)
      ElMessage.error(isEdit.value ? '修改失败' : '添加失败')
    }
  })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.dict-title {
  font-size: 16px;
  font-weight: bold;
}

.search-form {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 